package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.LoginPermission;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PipedReader;

/**
 * 登陆拦截器
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //如果是静态和跨域,就放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //放在外面表示无论是否有登陆都要刷新失效时间
        //从请求头获取token
        String token = request.getHeader("token");

        //凭借token获取user
        UserInfo user = userInfoRedisService.getRedisUser(token);


        //handler转为HandlerMethod类型
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //判断方法是否有LoginPermission 注解
        if (handlerMethod.hasMethodAnnotation(LoginPermission.class)){
            //判断user 是否为null, 为null,响应JsonResult
            if (user == null){
                //防止中文乱码
                response.setContentType("application/json;charset=utf-8");
                //响应JsonResult
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }

        //不为null, 放行
        return true;
    }
}
